﻿using BZ.Core.Frm;
using BZ.Core.TaskExt;
using BZ.Logger;
using DevComponents.DotNetBar;
using DevComponents.Schedule.Model;
using NDK.LocalUtils.Yield;
using NDK.Module.BLL;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Module.StationLogic;
using NDK.Motion.Sys;
using NDK.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace NDK.Frm
{
    public partial class Frm_Home : Form
    {
        private static log4net.ILog m_Logger = log4net.LogManager.GetLogger("Frm_Home");
        private Action<Chart, Label, Label, Label, Label, Label> updateResultsToChart;
        private double[] singleSizeYields, singleSizeNGCount, singleSizeTotals, singleSizeOKCount;
        List<string> nameList = new List<string>();
        List<MeasureSize> sizes = null;

        public static ObservableCollection<SunWayOEETime> OEEs = new ObservableCollection<SunWayOEETime>();

        private Frm_Home()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 窗体对象实例，单例模式,保证整个工程只有一个实例
        /// </summary>
        private static Frm_Home _instance;
        private static readonly object singletonLock = new object();
        public static Frm_Home Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new Frm_Home();
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// =================HOME界面加载=======================
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Frm_Home_Load(object sender, EventArgs e)
        {
            #region 初始化OEE
            Common.OEETimeMethod = new SunWayOEETimeMethod();
            Common.OEEYieldMethod = new SunWayOEEYieldMethodd();
            Common.OEEYieldUpLoadMethod = new SunWayOEEYieldUpLoadMethod();
            #endregion

            #region 初始化饼图
            List<string> xData = new List<string>() { "NG", "OK" };
            List<int> yData = new List<int>() { 0, 1 };
            chart1.Series["Series1"].Label = "#VALX:#PERCENT{P}";
            chart1.Series["Series1"].Points.DataBindXY(xData, yData);
            chart1.Series["Series1"].Points[0].Color = Color.Red;
            chart1.Series["Series1"].Points[1].Color = Color.Green;
            tb_Result.Font = new Font("Microsoft YaHei", 48F, FontStyle.Bold, GraphicsUnit.Point, 134);
            #endregion

            #region 绑定委托更新界面消息
            updateResultsToChart += AddResultsToChart;
            #endregion

            #region 更新界面数据列表
            RefreshHomeUI(Common.CurProType);
            #endregion

            #region 读取点检和上传线性文件
            PublicMethod.ReadCSVFile();
            #endregion

            #region 结果输出(dgv,chart,panel) 绑定更新界面函数
            ProcessData.UpdateUIEvent += new delegateUpdateUI(UpdataUI);
            ProcessData.UpdateNGUIEvent += new delegateUpdateNGUI(UpdataNGUI);
            #endregion

            #region 读入历史数据
            ReadHistoryData();
            #endregion

            #region 保存数据到csv
            tb_ext.Text = Common.SP_线体 + "_" + Common.startDate;//默认CSV文件名
            SunWayOEEYieldMethodd sunwayoee = new SunWayOEEYieldMethodd();
            Task.Factory.StartNew(() =>
            {
                int j = 0;

                //在输出文档的第二列增加NG/OK
                string Header = "Time,Position,Line,MeasureId,OK_NG,NG_FAI,Barcode";
                string USL = @",-,-,-,-,-,USL";
                string NOM = @",-,-,-,-,-,NOM";
                string LSL = @",-,-,-,-,-,LSL";

                MeasureSize measureSize;
                while (true)
                {
                    Thread.Sleep(5);
                    try
                    {
                        if (Common.Queue_SaveCsv.TryDequeue(out MeasureProduct measureProduct))
                        {
                            var time = DateTime.Now;
                            //创建存数据的路径
                            string CSVDataDirectory = $"{Common.dataSavePath}\\{Common.ProjectName}\\{time:yyyy-MM}\\{Common.CurProType} Data\\{time:yyyy-MM-dd}";
                            if (!Directory.Exists(CSVDataDirectory))
                            {
                                Directory.CreateDirectory(CSVDataDirectory);
                            }
                            string fullPath = $"{CSVDataDirectory}\\{tb_ext.Text.Trim()}.csv";
                            bool IsNew = !File.Exists(fullPath);
                            if (IsNew)
                            {
                                j = 0;
                                Header = "StartTime,EndTime,Pos,PPGPos,Line,MeasureId,OK_NG,NG_FAI,Barcode";
                                USL = ",-,-,-,-,-,-,-,USL";
                                NOM = ",-,-,-,-,-,-,-,NOM";
                                LSL = ",-,-,-,-,-,-,-,LSL";
                            }
                            j++;
                            StringBuilder strs = new StringBuilder();
                            strs.Append($"{measureProduct.TestStart:yyyy-MM-dd HH:mm:ss},{time:yyyy-MM-dd HH:mm:ss},{measureProduct.TurnTableHole},{measureProduct.PPGHole},{Common.SP_线体},{j},{measureProduct.OK_NG},{measureProduct.NG_FAI},{measureProduct.SN},");
                            var sizeSer = new MeasureSizeServices();
                            //List<string> NGFAI = new List<string>();
                            //NGFAI.Add(measureProduct.NG_FAI);
                            //sunwayoee.Refresh(time,Common.TotalCount,Common.OKCount,NGFAI);
                            List<MeasureSize> measureSizeList = sizeSer.GetAllByProjectNameAndTurnNum(Common.CurProType, measureProduct.TurnTableHole);
                            measureSizeList.AddRange(sizeSer.GetAllByProjectNameAndTurnNum(Common.CurProType, 0));
                            measureSizeList.Add(sizeSer.GetModelByProjectNameAndTurnNum(Common.CurProType, measureProduct.PPGHole + 10));
                            measureSizeList.RemoveAll(x => x == null);
                            measureSizeList.RemoveAll(x => x.IsShow == false);
                            foreach (var dataItem in measureProduct.MeasureData)
                            {
                                measureSize = measureSizeList.SingleOrDefault(x => x.SizeName == dataItem.Name);
                                if (measureSize == null)
                                    continue;
                                //保存到数据到CSV中  表头
                                strs.Append($"{dataItem.Value:f4},{dataItem.JugeResult},");
                                if (IsNew)
                                {
                                    Header += $",{measureSize.SizeName},Result";
                                    USL += $",{measureSize.UpperDeviation},-";
                                    NOM += $",{measureSize.NormValue},-";
                                    LSL += $",{measureSize.LowerDeviation},-";
                                }
                            }
                            //写csv表头
                            if (IsNew)
                            {
                                FileUtils.AppendText(fullPath, Header + "\r\n");
                                FileUtils.AppendText(fullPath, USL + "\r\n");
                                FileUtils.AppendText(fullPath, NOM + "\r\n");
                                FileUtils.AppendText(fullPath, LSL + "\r\n");
                            }
                            FileUtils.AppendText(fullPath, strs.ToString() + "\r\n");
                            if (Common.BP_UPMES)
                            {
                                var strDic = new Dictionary<string, Dictionary<string, string>>();
                                foreach (var dataItem in measureProduct.MeasureData)
                                {
                                    strDic.Add(dataItem.Name, new Dictionary<string, string>() { { "value", dataItem.Value.ToString() }, { "result", dataItem.JugeResult } });
                                }
                                string str = JsonConvert.SerializeObject(strDic);
                                var re = Common.SwMes.DataUpload(measureProduct.SN, str, measureProduct.OK_NG.ToString(), measureProduct.TestStart.ToString("yyyy-MM-dd HH:mm:ss"), time.ToString("yyyy-MM-dd HH:mm:ss"));
                                if (re.Item1)
                                {
                                    Common.AppendUiLog.Log($"{measureProduct.SN}上传数据OK", LogType.Alert);
                                }
                                else
                                {
                                    Common.AppendUiLog.Log(re.Item2 + re.Item3, LogType.Error);
                                    MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                                }
                            }
                            m_Logger.Debug("数据库和CSV保存线程正在运行...");
                        }

                    }
                    catch (Exception ex)
                    {
                        Common.AppendUiLog.Log("保存CSV数据异常!" + ex.ToString(), LogType.Error);
                        m_Logger.Debug("CSV保存异常");
                    }
                }
            });
            #endregion
        }

        public void ReadHistoryData()
        {
            Dictionary<string, string> dic = INIUtils.GetAllKeyValues(Common.CurProType);
            //投入数
            dic.TryGetValue("Total", out string strTotal);
            int.TryParse(strTotal, out Common.TotalCount);
            //OK数
            dic.TryGetValue("OKCount", out string strOKCount);
            int.TryParse(strOKCount, out Common.OKCount);
            //NG数
            Common.NGCount = Common.TotalCount - Common.OKCount;
            if (dic.Count > 0)
            {//单尺寸良率
                int count = dgv_ResultOutputRote.ColumnCount - 1;
                string[] singleSizeTotalss = new string[count];
                string[] singleSizeYieldss = new string[count];
                string[] singleSizeNGCountss = new string[count];
                for (int i = 0; i < count; i++)
                {
                    if (!dic.TryGetValue("singleSizeTotals" + i.ToString(), out singleSizeTotalss[i]))
                    {
                        singleSizeTotalss[i] = "0";
                        singleSizeYieldss[i] = "0";
                        singleSizeNGCountss[i] = "0";
                    }
                    else
                    {
                        dic.TryGetValue("singleSizeYields" + i.ToString(), out singleSizeYieldss[i]);
                        dic.TryGetValue("singleSizeNGCount" + i.ToString(), out singleSizeNGCountss[i]);
                    }
                }
                singleSizeTotals = Array.ConvertAll(singleSizeTotalss, x => double.Parse(x));
                singleSizeYields = Array.ConvertAll(singleSizeYieldss, x => double.Parse(x));
                singleSizeNGCount = Array.ConvertAll(singleSizeNGCountss, x => double.Parse(x));
            }

            AddResultsToChart(chart1, lbl_CT, lbl_Total, OKLab, NGLab, NALab);
            updataUI();
        }

        public int SortMeasureSize(MeasureSize x, MeasureSize y)
        {
            if (x.ID > y.ID)
                return 1;
            if (x.ID < y.ID)
                return -1;
            return 0;
        }

        public void RefreshHomeUI(string productType)
        {
            MeasureSizeServices measureSizeService = new MeasureSizeServices();
            sizes = measureSizeService.GetAllByProjectNameAndTurnNum(productType, 0);
            sizes.Add(measureSizeService.GetModelByProjectNameAndTurnNum(productType, 11));
            sizes.AddRange(measureSizeService.GetAllByProjectNameAndTurnNum(productType, 1));
            sizes.Sort(SortMeasureSize);
            if (sizes == null)
                return;

            int sizeCount = 0;
            nameList = new List<string>();
            List<DataGridViewTextBoxColumn> dgvColumns = new List<DataGridViewTextBoxColumn>();
            foreach (MeasureSize size in sizes)
            {
                if (size.IsShow)
                {
                    sizeCount++;
                    nameList.Add(size.SizeName);
                    var column = new DataGridViewTextBoxColumn()
                    {
                        FillWeight = 80,
                        ReadOnly = true,
                        Name = size.SizeName,
                        HeaderText = size.SizeName,
                        DataPropertyName = size.SizeName,
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    };
                    column.HeaderCell.Style.ForeColor = size.IsJudging ? Color.Green : Color.YellowGreen;
                    dgvColumns.Add(column);
                }
            }

            //设置固定列表头
            dgv_ResultOutput.Columns.Clear();
            dgv_NGResultOutput.Columns.Clear();
            dgv_ResultOutputRote.Columns.Clear();
            string[] str = new string[6] { " ", "NGFAI", "Time", "Barcode", "Pos", "PPGPos" };
            var FixColumn = new List<DataGridViewTextBoxColumn>();
            for (int i = 0; i < str.Length; i++)
            {
                FixColumn.Add(new DataGridViewTextBoxColumn()
                {
                    FillWeight = 80,
                    Name = str[i],
                    ReadOnly = true,
                    HeaderText = str[i],
                    DataPropertyName = str[i],
                    SortMode = DataGridViewColumnSortMode.NotSortable
                });
            }
            //良率表
            dgv_ResultOutputRote.Columns.Add((DataGridViewTextBoxColumn)FixColumn[0].Clone());
            dgvColumns.ForEach(x => dgv_ResultOutputRote.Columns.Add((DataGridViewTextBoxColumn)x.Clone()));
            //NG表
            FixColumn.ForEach(x => dgv_NGResultOutput.Columns.Add((DataGridViewTextBoxColumn)x.Clone()));
            dgvColumns.ForEach(x => dgv_NGResultOutput.Columns.Add((DataGridViewTextBoxColumn)x.Clone()));
            //OK表
            FixColumn.Where(x => x.Name != str[1]).ToList().ForEach(x => dgv_ResultOutput.Columns.Add((DataGridViewTextBoxColumn)x.Clone()));
            dgvColumns.ForEach(x => dgv_ResultOutput.Columns.Add((DataGridViewTextBoxColumn)x.Clone()));

            AddRow(dgv_ResultOutput, 5);
            AddRow(dgv_NGResultOutput, 6);

            singleSizeYields = new double[sizeCount];
            singleSizeNGCount = new double[sizeCount];
            singleSizeTotals = new double[sizeCount];
            singleSizeOKCount = new double[sizeCount];
            dgv_ResultOutputRote.BackgroundColor = Color.Black;
            dgv_ResultOutputRote.ForeColor = Color.Green;
            dgv_ResultOutputRote.Font = new Font("隶书", 12);
            dgv_ResultOutputRote.ReadOnly = true;

            void AddRow(DataGridView dgv, int value)
            {
                try
                {
                    dgv.Rows.Clear();
                    var DgvRow = new List<DataGridViewRow>();
                    for (int i = 0; i < 3; i++)
                    {
                        DgvRow.Add(new DataGridViewRow() { ReadOnly = true });
                        DgvRow[i].CreateCells(dgv);
                    }

                    for (int index = 0; index < dgv.Columns.Count; index++)
                    {
                        if (index < value)
                        {
                            if (index == 0)
                            {
                                DgvRow[0].Cells[0].Value = "Tol(+)";
                                DgvRow[1].Cells[0].Value = "Target";
                                DgvRow[2].Cells[0].Value = "Tol(-)";
                            }
                            else
                            {
                                DgvRow.ForEach(x => x.Cells[index].Value = "-");
                            }
                        }
                        else
                        {
                            var data = sizes.SingleOrDefault(x => x.SizeName == dgv.Columns[index].HeaderText);
                            DgvRow[0].Cells[index].Value = data.UpperDeviation.ToString();
                            DgvRow[1].Cells[index].Value = data.NormValue.ToString();
                            DgvRow[2].Cells[index].Value = data.LowerDeviation.ToString();
                        }
                        DgvRow.ForEach(x => x.Cells[index].Style.ForeColor = Color.White);
                        DgvRow.ForEach(x => x.Cells[index].Style.BackColor = Color.Black);
                        DgvRow.ForEach(x => x.Cells[index].Style.Font = new Font("隶书", 12));
                    }
                    DgvRow.ForEach(x => dgv.Rows.Add(x));
                    dgv.Rows[2].Frozen = true;      //冻结前三行
                }
                catch (Exception exc)
                {
                }
            }
        }

        #region UI
        /// <summary>
        /// 显示数据栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonItem_Data_Click(object sender, EventArgs e)
        {
            dotNetBarManager1.SuspendLayout = true;
            try
            {
                foreach (Bar bar in dotNetBarManager1.Bars)
                {
                    bar.TabNavigation = true;//防止拖拽后，导航栏消失
                    if (bar.DockSide == eDockSide.None)//防止拖拽后，未停靠到Document，就关闭tab
                    {
                        bar.DockSide = eDockSide.Document;
                    }
                    if (bar.DockSide == eDockSide.Document)
                    {
                        foreach (DockContainerItem dock in bar.Items)
                        {
                            if (dock.Name == "dockContainerItem_Data")
                            {
                                dock.Visible = true;
                                if (!bar.Visible)
                                    bar.Visible = true;
                            }
                        }
                    }
                }
            }
            finally
            {
                dotNetBarManager1.SuspendLayout = false;
            }
        }
        /// <summary>
        /// 显示所有栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonItem_All_Click(object sender, EventArgs e)
        {
            dotNetBarManager1.SuspendLayout = true;
            try
            {
                foreach (Bar bar in dotNetBarManager1.Bars)
                {
                    bar.TabNavigation = true;
                    if (bar.DockSide == eDockSide.None)
                    {
                        if (bar.Name == "bar_Statistics")
                        {
                            bar.DockSide = eDockSide.Left;
                        }
                        else if (bar.Name == "bar_Log")
                        {
                            bar.DockSide = eDockSide.Bottom;
                        }
                        else
                        {
                            bar.DockSide = eDockSide.Document;
                        }
                    }
                    if (bar.DockSide == eDockSide.Document
                        || bar.DockSide == eDockSide.Bottom
                        || bar.DockSide == eDockSide.Left
                        || bar.DockSide == eDockSide.Right)
                    {
                        foreach (DockContainerItem dock in bar.Items)
                        {
                            dock.Visible = true;
                            if (!bar.Visible)
                                bar.Visible = true;
                        }
                    }
                }
            }
            finally
            {
                dotNetBarManager1.SuspendLayout = false;
            }
        }
        /// <summary>
        /// 显示图像栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonItem_Image_Click(object sender, EventArgs e)
        {
            dotNetBarManager1.SuspendLayout = true;
            try
            {
                foreach (Bar bar in dotNetBarManager1.Bars)
                {
                    bar.TabNavigation = true;
                    if (bar.DockSide == eDockSide.None)
                    {
                        bar.DockSide = eDockSide.Document;
                    }
                    if (bar.DockSide == eDockSide.Document)
                    {
                        foreach (DockContainerItem dock in bar.Items)
                        {
                            if (dock.Name == "dockContainerItem_Image")
                            {
                                dock.Visible = true;
                                if (!bar.Visible)
                                    bar.Visible = true;
                            }
                        }
                    }
                }
            }
            finally
            {
                dotNetBarManager1.SuspendLayout = false;
            }
        }

        /// <summary>
        /// 显示日志栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonItem_Log_Click(object sender, EventArgs e)
        {
            dotNetBarManager1.SuspendLayout = true;
            try
            {
                foreach (Bar bar in dotNetBarManager1.Bars)
                {
                    if (bar.Name == "bar_Log")
                    {
                        bar.TabNavigation = true;
                        foreach (DockContainerItem dock in bar.Items)
                        {
                            dock.Visible = true;
                            if (!bar.Visible)
                                bar.Visible = true;
                        }
                        break;
                    }
                }
            }
            finally
            {
                dotNetBarManager1.SuspendLayout = false;
            }
        }
        #endregion

        #region 解决闪烁问题
        ///// <summary>
        ///// 解决闪烁问题
        ///// </summary>
        //protected override CreateParams CreateParams
        //{
        //    get
        //    {
        //        CreateParams cp = base.CreateParams;
        //        cp.ExStyle |= 0x02000000;
        //        return cp;
        //    }
        //}
        #endregion

        /// <summary>
        /// 更新饼图结果
        /// </summary>
        /// <param name="ret"></param>
        public void AddResultsToChart(Chart chart, Label lbl_CT, Label lbl_Total, Label OKLab, Label NGLab, Label NALab)
        {
            List<string> xData = new List<string>() { "NG", "OK" };
            SunWayOEEYieldMethodd sunwayoee = new SunWayOEEYieldMethodd();
            //SaveYieldToIni();
            List<int> yData = new List<int>() { Common.NGCount, Common.TotalCount - Common.NGCount };
            if (!lbl_CT.InvokeRequired)
            {
                chart.Series["Series1"].Label = "#VALX:#PERCENT{P}";

                chart.Series["Series1"].Points[0].Color = Color.Red;
                chart.Series["Series1"].Points[1].Color = Color.Green;
                chart.Series["Series1"].Points.DataBindXY(xData, yData);

                lbl_Total.Text = "Total:" + Common.TotalCount;
                OKLab.Text = (Common.TotalCount - Common.NGCount).ToString();
                NGLab.Text = Common.NGCount.ToString();

                //lbl_CT.Text = "CT: " + Common.TotalCT.ToString("0.000") + " S";
                //sunwayoee.Refresh(DateTime.Now, Common.TotalCount, Common.OKCount);// TOM修改
                double str = 100;
                if (Common.TotalCount == 0)
                {
                    str = 100.00;
                }
                else
                {
                    str = ((Common.TotalCount - Common.NGCount) / Common.TotalCount) * 100.00; //良率
                }
            }
            else
            {
                this.BeginInvoke(updateResultsToChart, new object[] { chart, lbl_CT, lbl_Total, OKLab, NGLab });
            }
        }

        /// <summary>
        /// 保存对应产品OK数和Total总数,保存各尺寸的良率
        /// </summary>
        public void SaveYieldToIni()
        {
            //保存对应产品OK数和Total总数
            INIUtils.Write(Common.CurProType, "OKCount", (Common.TotalCount - Common.NGCount).ToString());
            INIUtils.Write(Common.CurProType, "Total", (Common.TotalCount).ToString());
            INIUtils.Write(Common.CurProType, "ExceptionCount", (Common.ExceptionCount).ToString());

            //保存各尺寸的良率
            int count = dgv_ResultOutputRote.ColumnCount - 1;
            for (int i = 0; i < count; i++)
            {
                INIUtils.Write(Common.CurProType, "singleSizeTotals" + i.ToString(), singleSizeTotals[i].ToString());
                INIUtils.Write(Common.CurProType, "singleSizeYields" + i.ToString(), singleSizeYields[i].ToString());
                INIUtils.Write(Common.CurProType, "singleSizeNGCount" + i.ToString(), singleSizeNGCount[i].ToString());
            }
        }


        private void updataUI()
        {
            for (int index = 0; index < singleSizeTotals.Length; index++)
            {
                //计算单个尺寸的良率
                if (singleSizeTotals[index] != 0)
                {
                    singleSizeYields[index] = (singleSizeTotals[index] - singleSizeNGCount[index]) / Convert.ToDouble(singleSizeTotals[index]);
                }
                else
                {
                    singleSizeYields[index] = 0;
                }

                singleSizeOKCount[index] = singleSizeTotals[index] - singleSizeNGCount[index];

            }
            List<List<string>> strings = new List<List<string>>()
            {
                Array.ConvertAll(singleSizeYields,x => $"{x*100:f2}%").ToList(),
                Array.ConvertAll(singleSizeTotals,x => x.ToString()).ToList(),
                Array.ConvertAll(singleSizeOKCount,x => x.ToString()).ToList(),
                Array.ConvertAll(singleSizeNGCount,x => x.ToString()).ToList(),
            };
            strings[0].Insert(0, "Yield");
            strings[1].Insert(0, "Total");
            strings[2].Insert(0, "OK");
            strings[3].Insert(0, "NG");
            dgv_ResultOutputRote.Rows.Clear();
            for (int i = 0; i < strings.Count; i++)
            {
                dgv_ResultOutputRote.Rows.Add(strings[i].ToArray());
            }
        }

        private void Frm_Home_FormClosing(object sender, FormClosingEventArgs e)
        {
        }
        /// <summary>
        /// 导出home界面的数据到csv
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cms_OutputToCsv_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == tsmi_SaveToExcel)
            {
                //FileUtils.SaveCSV((DataTable)(dgv_ResultOutput.DataSource), @"D:\Data\output\data");
            }
        }
        /// <summary>
        /// 导出home界面的数据到csv
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cms_Log_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == tsmi_Clear)
            {
                dataGridViewLogBoard1.dataGridView.Rows.Clear();
            }
        }
        /// <summary>
        /// 不断更新home页面的CT显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_CT_Tick(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 更新数据到界面
        /// </summary>
        /// <param name="camaraDataList">当前测试产品的数据</param>
        private async void UpdataUI(MeasureProduct product)
        {
            List<DataItem> camaraDataList = product.MeasureData;
            if (camaraDataList == null)
                return;

            DataGridViewRow dr = new DataGridViewRow();
            try
            {
                await Task.Run(() =>
                {
                    dr.CreateCells(dgv_ResultOutput);
                    dr.Cells[1].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    dr.Cells[2].Value = product.SN;
                    dr.Cells[3].Value = product.TurnTableHole;
                    dr.Cells[4].Value = product.PPGHole;
                    for (int i = 0; i < nameList.Count + 5; i++)
                    {
                        if (i >= 5)
                        {
                            var value = camaraDataList.SingleOrDefault(x => x.Name == nameList[i - 5]);
                            if (value != null)
                            {
                                singleSizeTotals[i - 5]++;
                                dr.Cells[i].Value = value.Value.ToString("F4");
                            }
                        }
                        dr.Cells[i].Style.BackColor = Color.Black;
                        dr.Cells[i].Style.ForeColor = Color.LawnGreen;
                        dr.Cells[i].Style.Font = new Font("隶书", 12);
                    }
                });
                //新增加一行在第一行
                BeginInvoke(new Action(() =>
                {
                    updataUI();
                    if (dgv_ResultOutput.Rows.Count >= 64)
                    {
                        for (int i = 1; i <= 4; i++)
                        {
                            dgv_ResultOutput.Rows.RemoveAt(dgv_ResultOutput.Rows.Count - 1);
                        }
                    }
                    dgv_ResultOutput.Rows.Insert(3, dr);    //插入的数据作为第一行显示

                    tb_Result.Text = "OK";
                    txtBarcode.Text = product.SN;
                    tb_Result.ForeColor = Color.Green;

                    Yield.Instance.UpdateYield(true);
                    AddResultsToChart(chart1, lbl_CT, lbl_Total, OKLab, NGLab, NALab);
                }));
            }
            catch (Exception exc)
            {
            }
        }
        private void Btn_OEEYieldClear_Click(object sender, EventArgs e)
        {
            FileUtils.ClearFile(Common.OEEYieldMethod.OEEYieldDayFilePath);
            FileUtils.ClearFile(Common.OEEYieldMethod.OEEYieldNightFilePath);
            Common.OEEYieldMethod.Init();
        }

        //private async void button1_Click(object sender, EventArgs e)
        //{
        //    button1.Enabled = false;
        //    await Task.Run(async () =>
        //    {
        //        //for(int i = 1;i<=999999;i++)
        //        //{
        //        //    Common.OEETimeMethod.ChangeStatus(OEESSTATUS.RUN);
        //        //    await Task.Delay(TimeSpan.FromSeconds(3));
        //        //    Common.OEETimeMethod.ChangeStatus(OEESSTATUS.ALARM);
        //        //    await Task.Delay(TimeSpan.FromSeconds(4));
        //        //    Common.OEETimeMethod.ChangeStatus(OEESSTATUS.WAIT);
        //        //    await Task.Delay(TimeSpan.FromSeconds(3));
        //        //    Common.OEETimeMethod.ChangeStatus(OEESSTATUS.PLAN);
        //        //    await Task.Delay(TimeSpan.FromSeconds(3));
        //        //    Common.OEETimeMethod.ChangeStatus(OEESSTATUS.DOE);
        //        //    await Task.Delay(TimeSpan.FromSeconds(3));
        //        //    Common.OEETimeMethod.ChangeStatus(OEESSTATUS.RUN);
        //        //}
        //        Common.OEEYieldMethod.Refresh(DateTime.Now.AddHours(-6), 100, 1, new List<string>() {  "FAI3", "FAI4","FAI99","FAI88" });
        //        Common.OEEYieldMethod.Refresh(DateTime.Now, 100, 1, new List<string>() { "FAI1", "FAI2", "FAI3", "FAI4" });
        //        Common.OEEYieldUpLoadMethod.Upload();
        //    });
        //    button1.Enabled = true;
        //}

        /// <summary>
        /// 更新NG数据到界面
        /// </summary>
        /// <param name="camaraDataList">当前测试产品的数据</param>
        private async void UpdataNGUI(MeasureProduct product)
        {
            List<DataItem> camaraDataList = product.MeasureData;
            if (camaraDataList == null)
            { return; }
            DataGridViewRow dr = new DataGridViewRow();

            await Task.Run(() =>
            {
                dr.CreateCells(dgv_NGResultOutput);

                dr.Cells[1].Value = product.NG_FAI;
                dr.Cells[2].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                dr.Cells[3].Value = product.SN;
                dr.Cells[4].Value = product.TurnTableHole;
                dr.Cells[5].Value = product.PPGHole;
                dr.Cells[1].Style.ForeColor = Color.Red;
                for (int i = 0; i < nameList.Count + 6; i++)
                {
                    dr.Cells[i].Style.BackColor = Color.Black;
                    dr.Cells[i].Style.ForeColor = Color.LawnGreen;
                    dr.Cells[i].Style.Font = new Font("隶书", 12);
                    if (i >= 6)
                    {
                        var value = camaraDataList.SingleOrDefault(x => x.Name == nameList[i - 6]);
                        if (value != null)
                        {
                            singleSizeTotals[i - 6]++;
                            dr.Cells[i].Value = value.Value > 999 ? "N/A" : value.Value.ToString("F4");
                            if (value.JugeResult != JUDGEMENT_RESULT.OK.ToString())
                            {
                                singleSizeNGCount[i - 6]++;
                                dr.Cells[i].Style.ForeColor = Color.Red;
                            }
                        }
                    }
                }
            });

            BeginInvoke(new Action(() =>
            {
                try
                {
                    updataUI();
                    if (dgv_NGResultOutput.Rows.Count >= 64)
                    {
                        for (int i = 1; i <= 4; i++)
                        {
                            dgv_NGResultOutput.Rows.RemoveAt(dgv_NGResultOutput.Rows.Count - 1);
                        }
                    }

                    tb_Result.Text = "NG";
                    txtBarcode.Text = product.SN;
                    tb_Result.ForeColor = Color.Red;
                    dgv_NGResultOutput.Rows.Insert(3, dr);    //插入的数据作为第一行显示

                    Yield.Instance.UpdateYield(false);
                    AddResultsToChart(chart1, lbl_CT, lbl_Total, OKLab, NGLab, NALab);
                }
                catch (Exception exc)
                {
                }
            }));
        }

        /// <summary>
        /// 监控窗体点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == tsmi_MothionDebug)//工站步骤监控
            {
                Frm_StationDebug stationDebugFrm = Frm_StationDebug.Instance;
                stationDebugFrm.Show();
            }
            if (e.ClickedItem == tsmi_MonitorVar)//运行时变量监控
            {
                Frm_VarMonitor varMonitorFrm = new Frm_VarMonitor();
                varMonitorFrm.Show();
            }
            if (e.ClickedItem == tsmi_MonitorTask)//线程状态监控
            {
                Frm_TaskMonitor taskMonitorForm = new Frm_TaskMonitor();
                taskMonitorForm.Show();
            }
        }

        /// <summary>
        /// Chart图表 清空重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chart1_DoubleClick(object sender, EventArgs e)
        {
            FileUtils.ClearFile(INIUtils.Path);
            Common.NGCount = 0;
            Common.TotalCount = 0;
            Common.NACount = 0;
            Common.ExceptionCount = 0;

            for (int i = 0; i < singleSizeTotals.Length; i++)
            {
                singleSizeTotals[i] = 0;
                singleSizeYields[i] = 0;
                singleSizeNGCount[i] = 0;
            }

            AddResultsToChart(chart1, lbl_CT, lbl_Total, OKLab, NGLab, NALab);

            RefreshHomeUI(Common.CurProType);
        }
    }
}

